import { View, Text, TextInput, TouchableOpacity, FlatList, Image, StyleSheet, KeyboardAvoidingView, Platform, ActivityIndicator, Alert } from 'react-native';
import React, { useState, useEffect, useRef } from 'react';
import { useLocalSearchParams, Stack, useRouter } from 'expo-router';
import { useTheme } from '../../context/ThemeContext';
import { MaterialCommunityIcons } from '@expo/vector-icons';
import { getGroupHistory, sendMessage, MessageType, markMessagesAsRead, getGroupMembers, GroupMemberType } from '../../services/chatService';

export default function GroupChatScreen() {
  const { id, name } = useLocalSearchParams();
  const { isDarkMode } = useTheme();
  const router = useRouter();
  
  const [messages, setMessages] = useState<MessageType[]>([]);
  const [members, setMembers] = useState<GroupMemberType[]>([]);
  const [inputText, setInputText] = useState('');
  const [loading, setLoading] = useState(true);
  const [sending, setSending] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  
  const flatListRef = useRef<FlatList>(null);
  const userId = 1; // 假设当前用户ID为1，实际应从用户上下文或存储中获取
  
  // 加载群聊成员
  const loadGroupMembers = async () => {
    try {
      // 使用模拟数据
      const mockMembers: GroupMemberType[] = [
        {
          userId: 1,
          userName: '张三',
          userAvatar: 'https://randomuser.me/api/portraits/men/1.jpg',
          nickname: '组长',
          role: 2, // 群主
          joinTime: '2023-01-01 12:00:00'
        },
        {
          userId: 2,
          userName: '李四',
          userAvatar: 'https://randomuser.me/api/portraits/men/2.jpg',
          nickname: '李四',
          role: 0, // 普通成员
          joinTime: '2023-01-01 12:05:00'
        },
        {
          userId: 3,
          userName: '王五',
          userAvatar: 'https://randomuser.me/api/portraits/men/3.jpg',
          nickname: '王五',
          role: 1, // 管理员
          joinTime: '2023-01-01 12:10:00'
        },
      ];
      
      // 在实际应用中，这里应该调用API获取成员列表
      // const members = await getGroupMembers(Number(id));
      setMembers(mockMembers);
    } catch (error) {
      console.error('加载群成员失败:', error);
    }
  };
  
  // 加载聊天记录
  const loadMessages = async (page: number = 1) => {
    try {
      if (page === 1) {
        setLoading(true);
      }
      
      // 使用模拟数据
      const mockMessages: MessageType[] = [
        {
          id: 125,
          fromUserId: 1,
          fromUserName: '张三',
          fromUserAvatar: 'https://randomuser.me/api/portraits/men/1.jpg',
          toId: Number(id),
          chatType: 1,
          content: '大家好！',
          contentType: 0,
          status: 1,
          createTime: '2023-05-25 12:00:00'
        },
        {
          id: 126,
          fromUserId: 2,
          fromUserName: '李四',
          fromUserAvatar: 'https://randomuser.me/api/portraits/men/2.jpg',
          toId: Number(id),
          chatType: 1,
          content: '欢迎加入群组！',
          contentType: 0,
          status: 1,
          createTime: '2023-05-25 12:01:00'
        },
        {
          id: 127,
          fromUserId: 3,
          fromUserName: '王五',
          fromUserAvatar: 'https://randomuser.me/api/portraits/men/3.jpg',
          toId: Number(id),
          chatType: 1,
          content: '下午我们开个研讨会，讨论一下项目进度。',
          contentType: 0,
          status: 1,
          createTime: '2023-05-25 12:02:00'
        },
        {
          id: 128,
          fromUserId: 1,
          fromUserName: '张三',
          fromUserAvatar: 'https://randomuser.me/api/portraits/men/1.jpg',
          toId: Number(id),
          chatType: 1,
          content: '好的，我已经准备好了材料。',
          contentType: 0,
          status: 1,
          createTime: '2023-05-25 12:03:00'
        }
      ];

      // 在实际应用中，这里应该调用API获取消息
      // const response = await getGroupHistory(Number(id), page);
      const mockResponse = {
        records: mockMessages,
        total: mockMessages.length,
        size: 20,
        current: page,
        pages: 1
      };

      if (page === 1) {
        setMessages(mockResponse.records);
      } else {
        setMessages(prev => [...mockResponse.records, ...prev]);
      }
      
      setCurrentPage(page);
      setHasMore(page < mockResponse.pages);
      
      // 标记消息为已读
      // const unreadIds = mockResponse.records
      //   .filter(msg => msg.status === 0 && msg.fromUserId !== userId)
      //   .map(msg => msg.id);
      // if (unreadIds.length > 0) {
      //   await markMessagesAsRead(unreadIds);
      // }
      
    } catch (error) {
      console.error('加载消息记录失败:', error);
      Alert.alert('错误', '加载消息记录失败，请重试');
    } finally {
      setLoading(false);
    }
  };
  
  // 首次加载数据
  useEffect(() => {
    loadMessages();
    loadGroupMembers();
  }, [id]);
  
  // 发送消息
  const handleSend = async () => {
    if (!inputText.trim()) return;
    
    try {
      setSending(true);
      
      // 在实际应用中，这里应该调用API发送消息
      // const messageId = await sendMessage(Number(id), 1, inputText.trim());
      
      // 模拟消息发送
      const newMessage: MessageType = {
        id: Date.now(),
        fromUserId: userId,
        fromUserName: '张三', // 应该从用户上下文获取
        fromUserAvatar: 'https://randomuser.me/api/portraits/men/1.jpg',
        toId: Number(id),
        chatType: 1,
        content: inputText.trim(),
        contentType: 0,
        status: 1,
        createTime: new Date().toISOString().replace('T', ' ').substring(0, 19)
      };
      
      setMessages(prev => [...prev, newMessage]);
      setInputText('');
      
      // 滚动到底部
      setTimeout(() => {
        flatListRef.current?.scrollToEnd({ animated: true });
      }, 100);
      
    } catch (error) {
      console.error('发送消息失败:', error);
      Alert.alert('错误', '发送消息失败，请重试');
    } finally {
      setSending(false);
    }
  };
  
  // 加载更多消息
  const handleLoadMore = () => {
    if (hasMore && !loading) {
      loadMessages(currentPage + 1);
    }
  };
  
  // 格式化时间
  const formatTime = (timeStr: string) => {
    const date = new Date(timeStr);
    const now = new Date();
    
    if (date.toDateString() === now.toDateString()) {
      return timeStr.substring(11, 16); // 当天只显示时:分
    } else if (date.getFullYear() === now.getFullYear()) {
      return timeStr.substring(5, 16); // 当年显示月-日 时:分
    } else {
      return timeStr.substring(0, 16); // 其他显示年-月-日 时:分
    }
  };
  
  // 渲染消息项
  const renderMessageItem = ({ item }: { item: MessageType }) => {
    const isMyMessage = item.fromUserId === userId;
    
    return (
      <View
        style={[
          styles.messageContainer,
          isMyMessage ? styles.myMessageContainer : styles.otherMessageContainer
        ]}
      >
        {!isMyMessage && (
          <Image 
            source={{ uri: item.fromUserAvatar }} 
            style={styles.avatar}
          />
        )}
        
        <View style={styles.messageContentContainer}>
          {!isMyMessage && (
            <Text style={[
              styles.senderName,
              { color: isDarkMode ? '#BBBBBB' : '#666666' }
            ]}>
              {item.fromUserName}
            </Text>
          )}
          
          <View style={[
            styles.messageBubble,
            isMyMessage ? 
              [styles.myMessageBubble, { backgroundColor: isDarkMode ? '#007AFF' : '#007AFF' }] : 
              [styles.otherMessageBubble, { backgroundColor: isDarkMode ? '#333333' : '#E9E9EB' }]
          ]}>
            <Text style={[
              styles.messageText,
              { color: isMyMessage || isDarkMode ? '#FFFFFF' : '#000000' }
            ]}>
              {item.content}
            </Text>
          </View>
          
          <Text style={[
            styles.timeText,
            { color: isDarkMode ? '#999999' : '#999999' }
          ]}>
            {formatTime(item.createTime)}
          </Text>
        </View>
        
        {isMyMessage && (
          <Image 
            source={{ uri: item.fromUserAvatar }} 
            style={styles.avatar}
          />
        )}
      </View>
    );
  };

  return (
    <>
      <Stack.Screen options={{ 
        title: String(name),
        headerStyle: {
          backgroundColor: isDarkMode ? '#1E1E1E' : '#FFFFFF',
        },
        headerTintColor: isDarkMode ? '#FFFFFF' : '#333333',
        headerRight: () => (
          <TouchableOpacity onPress={() => router.push(`/chat/info/${id}?type=group`)}>
            <MaterialCommunityIcons 
              name="information-outline" 
              size={24} 
              color={isDarkMode ? '#FFFFFF' : '#333333'} 
            />
          </TouchableOpacity>
        ),
      }} />
      
      <KeyboardAvoidingView 
        style={[
          styles.container,
          { backgroundColor: isDarkMode ? '#121212' : '#F5F5F5' }
        ]}
        behavior={Platform.OS === "ios" ? "padding" : "height"}
        keyboardVerticalOffset={Platform.OS === "ios" ? 90 : 0}
      >
        {/* 消息列表 */}
        {loading && messages.length === 0 ? (
          <View style={styles.loadingContainer}>
            <ActivityIndicator size="large" color={isDarkMode ? '#3B82F6' : '#2563EB'} />
            <Text style={{ color: isDarkMode ? '#BBBBBB' : '#666666', marginTop: 10 }}>
              加载消息中...
            </Text>
          </View>
        ) : (
          <FlatList
            ref={flatListRef}
            data={messages}
            renderItem={renderMessageItem}
            keyExtractor={item => item.id.toString()}
            contentContainerStyle={styles.messagesList}
            onEndReached={handleLoadMore}
            onEndReachedThreshold={0.1}
            inverted={false}
            ListEmptyComponent={
              <View style={styles.emptyContainer}>
                <Text style={{ color: isDarkMode ? '#BBBBBB' : '#999999' }}>
                  暂无消息记录
                </Text>
              </View>
            }
            ListHeaderComponent={
              hasMore ? (
                <View style={styles.loadMoreContainer}>
                  <ActivityIndicator size="small" color={isDarkMode ? '#3B82F6' : '#2563EB'} />
                  <Text style={{ color: isDarkMode ? '#BBBBBB' : '#999999', marginLeft: 10 }}>
                    加载更多...
                  </Text>
                </View>
              ) : null
            }
          />
        )}
        
        {/* 输入框 */}
        <View style={[
          styles.inputContainer,
          { backgroundColor: isDarkMode ? '#1A1A1A' : '#FFFFFF' }
        ]}>
          <TextInput
            style={[
              styles.input,
              { 
                backgroundColor: isDarkMode ? '#2A2A2A' : '#F0F0F0',
                color: isDarkMode ? '#FFFFFF' : '#000000'
              }
            ]}
            placeholder="输入消息..."
            placeholderTextColor={isDarkMode ? '#999999' : '#999999'}
            value={inputText}
            onChangeText={setInputText}
            multiline
          />
          
          <TouchableOpacity
            style={[
              styles.sendButton,
              { backgroundColor: isDarkMode ? '#3B82F6' : '#2563EB' }
            ]}
            onPress={handleSend}
            disabled={sending || !inputText.trim()}
          >
            {sending ? (
              <ActivityIndicator size="small" color="#FFFFFF" />
            ) : (
              <MaterialCommunityIcons name="send" size={20} color="#FFFFFF" />
            )}
          </TouchableOpacity>
        </View>
      </KeyboardAvoidingView>
    </>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  messagesList: {
    padding: 10,
  },
  messageContainer: {
    flexDirection: 'row',
    marginVertical: 8,
    alignItems: 'flex-end',
  },
  myMessageContainer: {
    justifyContent: 'flex-end',
  },
  otherMessageContainer: {
    justifyContent: 'flex-start',
  },
  messageContentContainer: {
    maxWidth: '75%',
    marginHorizontal: 8,
  },
  senderName: {
    fontSize: 12,
    marginBottom: 3,
    marginLeft: 5,
  },
  avatar: {
    width: 36,
    height: 36,
    borderRadius: 18,
  },
  messageBubble: {
    padding: 10,
    borderRadius: 16,
  },
  myMessageBubble: {
    borderBottomRightRadius: 4,
  },
  otherMessageBubble: {
    borderBottomLeftRadius: 4,
  },
  messageText: {
    fontSize: 16,
  },
  timeText: {
    fontSize: 10,
    alignSelf: 'flex-end',
    marginTop: 3,
    marginRight: 5,
  },
  inputContainer: {
    flexDirection: 'row',
    padding: 10,
    alignItems: 'center',
    borderTopWidth: 1,
    borderTopColor: '#EEEEEE',
  },
  input: {
    flex: 1,
    borderRadius: 20,
    paddingHorizontal: 15,
    paddingVertical: 10,
    maxHeight: 100,
  },
  sendButton: {
    width: 40,
    height: 40,
    borderRadius: 20,
    justifyContent: 'center',
    alignItems: 'center',
    marginLeft: 10,
  },
  emptyContainer: {
    alignItems: 'center',
    justifyContent: 'center',
    paddingTop: 100,
  },
  loadMoreContainer: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    paddingVertical: 10,
  }
}); 